﻿using System;
using Microsoft.SharePoint.Administration;

namespace SPOffline.Web
{
    /// <summary>
    /// Persisted settings for each web application.
    /// </summary>
    public class SPOfflineSettings : SPPersistedObject
    {
        [Persisted] public bool IsOnline = true;
        [Persisted] public string OfflineMessage = string.Empty;

        /// <summary>
        /// Initializes a new instance of the <see cref="SPOfflineSettings"/> class.
        /// </summary>
        public SPOfflineSettings() { }

        /// <summary>
        /// Initializes a new instance of the <see cref="SPOfflineSettings"/> class.
        /// </summary>
        /// <param name="name">The name.</param>
        /// <param name="parent">The parent.</param>
        /// <param name="id">The id.</param>
        public SPOfflineSettings(string name, SPPersistedObject parent, Guid id)
            : base(name, parent, id)
        {
        }

        /// <summary>
        /// Gets the settings.
        /// </summary>
        /// <param name="webApplication">The web application.</param>
        /// <returns>The settings.</returns>
        public static SPOfflineSettings GetSettings(SPWebApplication webApplication)
        {
            var settings = webApplication.GetChild<SPOfflineSettings>(Constants.SettingsId);
            if (settings == null)
            {
                // create if doesn't exist
                return CreateNew(webApplication);
            }
            return settings;
        }

        /// <summary>
        /// Creates a new settings object.
        /// </summary>
        /// <param name="webApplication">The web application.</param>
        /// <returns>The settings.</returns>
        public static SPOfflineSettings CreateNew(SPWebApplication webApplication)
        {
            return new SPOfflineSettings(Constants.SettingsId, webApplication, Guid.NewGuid());
        }

    }

}
